package vip.xiaonuo.vehicle.common.util.transaction;

import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import vip.xiaonuo.core.exception.ServiceException;

import javax.annotation.Resource;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 事务工具类
 *
 * @author cad
 * @date 2023/03/23
 */
@Component
public class TransactionUtils {
    @Resource
    private DataSourceTransactionManager dataSourceTransactionManager;
    @Resource
    private TransactionDefinition transactionDefinition;

    /**
     * 开启事务
     */
    public TransactionStatus begin() {
        return dataSourceTransactionManager.getTransaction(transactionDefinition);
    }

    /**
     * 提交事务
     */
    public void commit(TransactionStatus transaction) {
        dataSourceTransactionManager.commit(transaction);
    }

    /**
     * 回滚事务
     */
    public void rollback(TransactionStatus transaction) {
        dataSourceTransactionManager.rollback(transaction);
    }

    /**
     * 用于多线程事务一致
     *
     * @param transactionCallBack 回调接口
     * @param cb                  线程屏障
     * @param rollback            回滚
     */
    public void multithreadedTransaction(TransactionCallBack transactionCallBack, CyclicBarrier cb, AtomicReference<Boolean> rollback) {
        //开启事务
        TransactionStatus transactionStatus = begin();
        try {
            //业务代码
            transactionCallBack.action();
            cb.await();
            if (rollback.get()) {
                rollback(transactionStatus);
                return;
            }
            commit(transactionStatus);
        } catch (Exception e) {
            rollback.set(true);
            rollback(transactionStatus);
            throw new ServiceException(500, "出现异常，整体回滚");
        }
    }
}
